package com.hlk.emos.wx.config.shiro;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author hlk
 * @version 1.0
 * @date 2021-05-18 17:08
 */
@Component
public class JwtUtil {
    @Autowired
    private JwtConfig jwtConfig;

    /**
     * 创建token
     *
     * @param userId
     * @return
     */
    public String createToken(int userId) {
        DateTime date = DateUtil.offsetDay(new Date(), jwtConfig.getExpire());
        Algorithm algorithm = Algorithm.HMAC256(jwtConfig.getSecret());
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        return token;
    }

    /**
     * 从token中获取用户ID
     *
     * @param token
     * @return
     */
    public int getUserId(String token) {
        DecodedJWT jwt = JWT.decode(jwtConfig.getSecret());
        Integer userId = jwt.getClaim("userId").asInt();
        return userId;
    }

    /**
     * 校验token
     *
     * @param token
     */
    public void verifierToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(jwtConfig.getSecret());
        JWT.require(algorithm).build().verify(token);
    }
}
